package com.cwt.common.utils;

import com.cwt.common.log.LogModel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author chenwt
 * @version V1.0
 * @describe 【】
 * @date 2022年12月01日 17:54:36
 */
public class ExcelUtil {

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = System.lineSeparator();


    /**
     * @param response 响应流
     * @param fileName 文件名称
     * @param titleColumn 标题列名称对象（如：name）
     * @param titleName 标题列名称对象描述（如：张三）
     * @param dataList  数据源
     */
    public static void writeCSV(HttpServletResponse response, String fileName, String titleColumn[], String titleName[], List<?> dataList) {
        OutputStream out = null;
        try {
            // 保证线程安全
            StringBuilder buf = new StringBuilder();
            out = response.getOutputStream();
            String lastFileName = fileName + ".csv";
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(lastFileName, "UTF-8"));

            // 组装表头
            for (String title : titleName) {
                buf.append(title).append(CSV_COLUMN_SEPARATOR);
            }
            buf.append(CSV_ROW_SEPARATOR);

            //组装行数据
            for (int index = 0; index < dataList.size(); index++) {
                Object obj = dataList.get(index);
                Class clazz = obj.getClass();
                for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                    String title = titleColumn[columnIndex].trim();
                    if (!"".equals(title)) {
                        // 获取返回类型
                        String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
                        String methodName = "get" + UTitle;
                        Method method = clazz.getDeclaredMethod(methodName);
                        Object object = method.invoke(obj);
                        //获取到数据
                        String data = method.invoke(obj) == null ? "" : object.toString();
                        //组装数据
                        buf.append(data).append(CSV_COLUMN_SEPARATOR);
                    }
                }
                buf.append(CSV_ROW_SEPARATOR);
            }
            //输出
            out.write(buf.toString().getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    LogModel.error("导出写Csv异常");
                }
            }
        }
    }

}
